<template>
	<view> 
		  
	 
        <view class="uni-padding-wrap" style="padding-bottom:120upx">
            <text>点击麦克风朗读</text>          
            <block v-if="!recording && !playing && !hasRecord">
                <view class="page-body-time">
                    <text class="time-big">{{formatedRecordTime}}</text>
                </view>
                <view class="page-body-buttons">
                    <view class="page-body-button"></view>
                    <view class="page-body-button" @click="startRecord">
                        <image src="../../static/record.png"></image>
                    </view>
                    <view class="page-body-button"></view>
                </view>
            </block>
            <block v-if="recording === true">
                <view class="page-body-time">
                    <text class="time-big">{{formatedRecordTime}}</text>
                </view>
                <view class="page-body-buttons">
                    <view class="page-body-button"></view>
                    <view class="page-body-button" @click="stopRecord">
                        <view class="button-stop-record"></view>
                    </view>
                    <view class="page-body-button"></view>
                </view>
            </block>
            <block v-if="hasRecord === true && playing === false && hasup===false">
                <view class="page-body-time">
                    <text class="time-big">{{formatedPlayTime}}</text>
                    <text class="time-small">{{formatedRecordTime}}</text>
                </view>
                <view class="page-body-buttons">
                    <view class="page-body-button" @click="playVoice">
                        <image src="../../static/play.png"></image>
                    </view>
                    <view class="page-body-button" @click="clear">
                        <image src="../../static/trash.png"></image>
                    </view>
                </view>
				<button type="primary" plain="true" @click="uploadRecord">录音上传</button>
            </block>
            <block v-if="hasRecord === true && playing === true">
                <view class="page-body-time">
                    <text class="time-big">{{formatedPlayTime}}</text>
                    <text class="time-small">{{formatedRecordTime}}</text>
                </view>
                <view class="page-body-buttons">
                    <view class="page-body-button" @click="stopVoice">
                        <image src="../../static/stop.png"></image>
                    </view>
                    <view class="page-body-button" @click="clear">
                        <image src="../../static/trash.png"></image>
                    </view>
                </view>
            </block>
        </view>
  
		</view>
	</view>
</template>
<script>
	// #ifdef APP-PLUS
	import permision from "@/common/permission.js"
	// #endif
	var FAIL_CONTENT = '<p>获取信息失败</p>';
	var api = require('@/common/api.js');
	var util = require('@/common/util.js');
    var playTimeInterval = null;
    var recordTimeInterval = null;
	var recorderManager = null;
	var page = 1,
		reachbottom = true;	
    var music = null;	
	import uniIcon from '@/components/uni-icon.vue';	
	export default {
		computed: {
			Screen_width() {
				return uni.getSystemInfoSync().windowWidth;
			}
		},
		data() {
			return {
				userinfo: "",
				banner: {},
				content: '',
				excerpt: '',
				comment_count: 0,
				like_count: 0,
				favorites_count: 0,
				hits_count: 0,
				ismark: false,
				title: 'start/stopRecord、play/stopVoice',
                recording: false, //录音中
                playing: false, //播放中
				hasRecord: false, //是否有了一个
				hasup:false,  //判断是否上传了
                tempFilePath: '',
                recordTime: 0,
                playTime: 0,
                formatedRecordTime: '00:00:00', //录音的总时间
				formatedPlayTime: '00:00:00', //播放录音的当前时间
				recordlist:[],  //回复列表
				id: '',
				playId: '',//播放的id
				pauseId: '',//暂停的id
				finiteId: '',//完成的id，如果想监听所有的，可以写一个数组队列						
			}
		},
		components: {
			uniIcon
		},
		onShareAppMessage() {
			return {
				title: this.banner.title,
				path: '/pages/article/article?query=' + encodeURIComponent(JSON.stringify(detail))
			}
		},
		//下拉刷新
		onPullDownRefresh() {
			page = 1
			reachbottom = true
			this.recordlist = []
			this.getDetail()
			this.getRecordList()
			uni.stopPullDownRefresh();
		},
		// 加载更多
		onReachBottom: function() {
			if (reachbottom) {				
				this.getRecordList();
			}
		},
		onShow() {
			/**const res = uni.getSystemInfoSync()
			// 计算主体部分高度,单位为px
			this.secondHeight = res.windowHeight
			if (reachbottom) {
				this.getRecordList()
			}*/
		},
		onUnload: function() {
			this.end();
			page = 1;
			reachbottom = true;
			this.getRecordList()
        },
		onLoad(event) {
			this.userinfo = uni.getStorageSync('user');				
			if (!event.id) {
				try {
					this.banner = JSON.parse(decodeURIComponent(event.query));
					//console.log(this.banner);
				} catch (error) {
					this.banner = JSON.parse(event.query);
				}
				this.excerpt = this.banner.desc;
				this.getDetail();
				uni.setNavigationBarTitle({
					title: this.banner.title
				});
			} else {
				api.get({
					url: '/portal/articles/' + event.id,
					success: (result) => {
						//console.log(result);
						if (result.code == 1) {
							var res = result.data
							//console.log(result.data);
							this.banner.id = res.id;
							this.banner.title = res.post_title;
							this.banner.datetime = res.published_time;
							this.banner.image_url = res.thumbnail;
							this.content = res.post_content;
							this.excerpt = res.post_excerpt;
							this.comment_count = res.comment_count;
							this.like_count = res.post_like;
							this.favorites_count = res.post_favorites;
							this.hits_count = res.post_hits;
						} else {
							this.content = FAIL_CONTENT;
						}
					}
				});
			}			
            music = uni.createInnerAudioContext();
            music.onEnded(() => {
                clearInterval(playTimeInterval)
                var playTime = 0
                console.log('play voice finished')
                this.playing = false;
                this.formatedPlayTime = util.formatTime(playTime);
                this.playTime = playTime;
            });
            recorderManager = uni.getRecorderManager();
            recorderManager.onStart(() => {
                console.log('recorder start');

                this.recording = true;
                recordTimeInterval = setInterval(() => {
                    this.recordTime += 1;
                    this.formatedRecordTime = util.formatTime(this.recordTime);
                }, 1000)
            });
            recorderManager.onStop((res) => {
                console.log('on stop');
                music.src = res.tempFilePath;
                this.hasRecord = true;
                this.recording = false;
            });
            recorderManager.onError(() => {
                console.log('recorder onError');
			});
			this.getRecordList();
			this.listenFun();			
		},		
		methods: {
			getDetail() {
				 
			},			
			async startRecord() { //开始录音
                // #ifdef APP-PLUS
                let status = await this.checkPermission();
                if (status !== 1) {  return; }
                // #endif 
                // TODO ios 在没有请求过权限之前无法得知是否有相关权限，这种状态下需要直接调用录音，但没有状态或回调判断用户拒绝
				 //默认是60000也即1分钟，修改这个参数可以改为10分钟
                recorderManager.start({ format: 'mp3', duration:600000  });
            },
            stopRecord() { //停止录音
                recorderManager.stop();
                clearInterval(recordTimeInterval);
            },
            playVoice() {
                console.log('play voice');
                this.playing = true;
                playTimeInterval = setInterval(() => {
                    this.playTime += 1;
                    this.formatedPlayTime = util.formatTime(this.playTime);
                }, 1000)
                music.play();
            },
            stopVoice() {
                clearInterval(playTimeInterval)
                this.playing = false;
                this.formatedPlayTime = util.formatTime(0);
                this.playTime = 0;
                music.stop();
            },
            end() {
                music.stop();
                recorderManager.stop();
                clearInterval(recordTimeInterval)
                clearInterval(playTimeInterval);
                this.recording = false, this.playing = false, this.hasRecord = false;
                this.playTime = 0, this.recordTime = 0;
                this.formatedRecordTime = "00:00:00", this.formatedRecordTime = "00:00:00";
			},
			uploadRecord(){ 
				api.uploadFile({
					url: '/portal/record/record_upload', //上传接口
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 默认值
					},
					filePath: music.src,
					name: 'file',
					formData: {
						'user_nick': this.userinfo.user_nickname,
						'user_head': this.userinfo.avatar,
						'post_id': this.banner.id,
						'src':    music.src
					},
					success: (uploadFileRes) => {
						uni.showToast({ title: '朗读成功', duration: 2000
						});
						this.hasup = true;  //避免重复提交
					}
        		});
			},
            clear() {
                this.end();
			},
			getRecordList() { 
				api.get({
					url: 'portal/record/getRecords',
					data: {
						page: page + ',7',
						post_id:this.banner.id
					},
					success: data => { 
						  
						uni.stopPullDownRefresh();
						 
					}
				});
			},
			//音频函数
			audioFun(records){
				this.id = records.id;
				if(records.id !== this.playId){//判断播放(或者暂停)的id和点击的是否一样
					this.innerAudioContext.stop();//兼容小程序(解决切换其他音频继续播放之前的音频)
					this.innerAudioContext.src = api.HOST+'/upload/'+records.recordpath;//重新赋值，会自动暂停所有的音频
				}
				if(!this.innerAudioContext.paused){//是播放状态我们就暂停
					this.innerAudioContext.pause();
				}else{
					this.innerAudioContext.play();//是暂停状态我们就播放
					this.playId = records.id;//只要播放我们就把这个id保存下来
					this.pauseId = '';//重置暂停id
					this.finiteId = '';//重置完成id
				}
			},
			//监听事件和注册实例
			listenFun(){
				//创建一个音频实例
				this.innerAudioContext = uni.createInnerAudioContext();
				//监听暂停的事件同步视图
				this.innerAudioContext.onPlay(() => {
					console.log('开始播放')
				})
				//监听暂停的事件同步视图
				this.innerAudioContext.onPause(() => {
					this.pauseId = this.id;
					console.log('暂停播放')
				})
				//监听播放完成事件同步视图
				this.innerAudioContext.onEnded(() => {
					this.finiteId = this.id;
					console.log('完成播放');
				})
			}		
            // #ifdef APP-PLUS
            ,
            async checkPermission() {
                let status = permision.isIOS ? await permision.requestIOS('record') :
                    await permision.requestAndroid('android.permission.RECORD_AUDIO');

                if (status === null || status === 1) {
                    status = 1;
                } else if (status === 2) {
                    uni.showModal({  content: "系统麦克风已关闭",  confirmText: "确定",
                        showCancel: false,   success: function(res) {  }
                    })
                } else {
                    uni.showModal({  content: "需要麦克风权限", confirmText: "设置",
                        success: function(res) {
                            if (res.confirm) {
                                permision.gotoAppSetting();
                            }
                        }
                    })
                }
                return status;
            }
            // #endif	
			,	
			//文章收藏
			doFavorite() {},
			//点赞doLike() {},
			comment() {
				uni.navigateTo({
					url: '/pages/comment/comment?id=' + this.banner.id
				})
			},
		}
	}
</script> 